import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { DatePicker, Form, Input, Radio } from 'antd';
import ModalUtil from '@/utils/modal.js';
import FormModal from '@/components/FormModal/index.jsx';
import RoleSelect from '@/pages/UserManage/widget/RoleSelect/index.jsx';
import { UserApi } from '@/api/user/api.js';
import { DATETIME_FORMAT, FORBIDDEN_USER_IDS } from '@/constants/CommonConstant.js';
import DayjsUtil from '@/utils/dayjs.js';
import { AvatarUpload } from '@/components/index.jsx';

export default forwardRef(function UserFormModal({ onRefresh }, ref) {
  useImperativeHandle(ref, () => ({
    openEdit: (data) => openEdit(data),
    openAdd: () => openAdd(),
    close: () => formRef.current?.close()
  }));

  const [form] = Form.useForm();
  const [isEdit, setIsEdit] = useState(false);
  const formRef = useRef(null);
  const [updateId, setUpdateId] = useState();
  const statusWatch = Form.useWatch('status', form);
  const usernameWatch = Form.useWatch('username', form);

  // 打开编辑弹窗
  function openEdit(data) {
    setIsEdit(true);
    if (data.userId == null) {
      setIsEdit(false);
      ModalUtil.error('数据ID丢失，请刷新重试');
      return;
    }
    setUpdateId(data.userId);
    formRef.current?.open();
    form.setFieldsValue(data);
  }

  // 打开新增弹窗
  function openAdd() {
    setIsEdit(false);
    formRef.current?.open();
    form?.resetFields();
  }

  // 提交表单
  const handleSubmit = async (values) => {
    let isSuccess = false;
    handleBeforeSubmit(values);
    if (isEdit) {
      const { code } = await UserApi.update(updateId, values);
      if (code === 0) {
        isSuccess = true;
      }
    } else {
      if (values?.password !== values?.confirmPassword) {
        ModalUtil.error('两次密码不一致');
        return;
      }
      const { code } = await UserApi.add(values);
      if (code === 0) {
        isSuccess = true;
      }
    }
    if (isSuccess) {
      ModalUtil.success('操作成功');
      form?.resetFields();
      onRefresh && onRefresh();
      formRef.current?.close();
    }
  };

  // 提交表单前置处理
  const handleBeforeSubmit = (values) => {
    if (Array.isArray(values?.roleList) && values?.roleList?.length > 0) {
      // 判断数组的值是否为字符串
      if (typeof values.roleList[0] != 'string') {
        const roleList = values.roleList.map((item) => item?.roleCode);
        values.roleList = roleList.filter((item) => item != null);
      }
    }
  };

  return (
    <>
      <FormModal
        form={form}
        ref={formRef}
        name="userForm"
        title={isEdit ? '编辑用户' : '新增用户'}
        onFinish={handleSubmit}
        formItems={
          <>
            {isEdit ? (
              <Form.Item name="avatar" label="头像">
                <AvatarUpload username={usernameWatch} />
              </Form.Item>
            ) : null}
            <Form.Item name="nickname" label="昵称" rules={[{ message: '请输入昵称' }]}>
              <Input />
            </Form.Item>
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input disabled={isEdit} />
            </Form.Item>
            {!isEdit ? (
              <>
                <Form.Item
                  name="password"
                  label="密码"
                  rules={[{ required: true, message: '请输入密码' }]}
                >
                  <Input.Password />
                </Form.Item>
                <Form.Item
                  name="confirmPassword"
                  label="确认密码"
                  rules={[{ required: true, message: '请输入确认密码' }]}
                >
                  <Input.Password />
                </Form.Item>
              </>
            ) : null}
            {isEdit ? (
              <>
                {FORBIDDEN_USER_IDS.includes(updateId) ? null : (
                  <>
                    <Form.Item
                      name="status"
                      label="状态"
                      rules={[{ required: true, message: '请选择状态' }]}
                      initialValue="1"
                    >
                      <Radio.Group
                        options={[
                          { label: '启用', value: '1' },
                          { label: '临时封禁', value: '2' },
                          { label: '永久封禁', value: '3' }
                        ]}
                        optionType="button"
                        buttonStyle="solid"
                      />
                    </Form.Item>
                    <Form.Item
                      name="suspendedTime"
                      label="临时封禁时间"
                      style={{ display: statusWatch === '2' ? 'block' : 'none' }}
                      getValueProps={(value) => ({
                        value: value ? DayjsUtil.dayjs(value) : null
                      })}
                      getValueFromEvent={(date) => date?.format(DATETIME_FORMAT)}
                    >
                      <DatePicker format={DATETIME_FORMAT} showTime style={{ width: '100%' }} />
                    </Form.Item>
                  </>
                )}
              </>
            ) : null}
            {FORBIDDEN_USER_IDS.includes(updateId) ? null : (
              <Form.Item
                name="roleList"
                label="角色"
                getValueProps={(value) => {
                  if (Array.isArray(value)) {
                    value = value.map((item) => {
                      // 如果是对象，则取对象的permissionCode字段，否则直接返回
                      return typeof item === 'object' ? item?.roleCode : item;
                    });
                  }
                  return { value: value };
                }}
              >
                <RoleSelect />
              </Form.Item>
            )}
          </>
        }
      />
    </>
  );
});
